Activity 8-2 - Streams as Arguments to Functions



A stream can be the argument to a function.  The only restriction is that any input or output must be passed to a function must be passed as call-by-reference.  Here is a modified version of P81.cpp in which we have used a function that reads a file name and then returns a stream, in_s, that is connected to that file to the main function.

// P81.cpp - This program reads some integers from a file and displays:
// The number, number^2, and the sum of all numbers read up to that point
#include<iostream>
#include<fstream> // Step (1)
#include<cstdlib>
#include<cmath>
using namespace std;

void get_stream(ifstream& in_s); // added function

int main( )
{
    double x;

    int count = 0;
    float sum = 0, avg;

    ifstream in_s; // Step (2)-B - declaration of the stream of type input

    get_stream(in_s);

    cout << "\t x \t\t x^2 \t\t Current Sum \n";
    cout << "\t === \t\t === \t\t ========== \n";

    while( in_s >> x) // Step (4)-Read all numbers one-by-one to the end of the file
    {
         sum = sum + x;
         cout << "\t " << x <<"\t\t " << pow(x,2) << "\t\t " << sum << "\n";
   count++;
    }

 avg = sum/count;
 cout << "\n \t\t The average of these " << count << " numbers is: " << avg << endl;

    in_s.close( ); // Step (5)-Close the connection (close the file)

   return 0;
}

 void get_stream(ifstream& in_s)
{
    char input_file[15]; // Step (2)-A
    cout << "Please input the input file name \n"; // Step (3)-A Get the file name
    cin >> input_file;

    in_s.open(input_file); // Step (3)-B - connect to the input file and test
    if(in_s.fail( ))
    {
       cout << "Input file opening failed. \n";
       exit(1); // if we couldn't open the file to read from we exit
    }
}

Exercise 8.3
Modify the above program such that the program writes the output file output.txt.  You need to modify the function get_stream such that it returns two streams to the main, one for the input and the other for the output.  Call your new program ex83.cpp.